<!--
 * 背景-纯色
 * @Author: xurenda <xurenda@qq.com>
 * @HomePage: https://xurenda.top
 * @Github: https://github.com/xurenda
 * @Date: 2019-10-13 12:32:24
 * @LastEditTime: 2019-12-06 20:35:53
 * @FilePath: \elegant-surf\src\components\background\Colors.vue
 -->
<template>
<div id="colors">
  <div
    v-for="(color, index) in backgroundColors"
    :key="index"
    :style="{ backgroundColor: color }"
    @click="changeBackgroundColor(color)"
  ></div>
  <div
    class="add-color"
    title="添加背景颜色"
    @click="isModalShow = true"
  >
    <i class="iconfont icon-tianjia-copy"></i>
  </div>
  
  <!-- 弹出 添加背景颜色 -->
  <modal v-if="isModalShow">
    <template #title>添加背景颜色</template>
    <template #default>
      <label>
        <div>6位 #RGB 颜色：</div>
        <input ref="input" type="text" placeholder="e.g. #ffffff" />
      </label>
    </template>
    <template #buttons>
      <button @click="isModalShow = false">取消</button>
      <button @click="addBackgroundColor">确定</button>
    </template>
  </modal>
</div>
</template>

<script>
import Modal from '@/components/common/Modal'
import { mapState } from 'vuex'
import { BACKGROUND_COLOR, ADD_BACKGROUND_COLOR } from '@/store/mutationsTypes'

export default {
  name: 'colors',
  components: { Modal },
  data() {
    return {
      isModalShow: false
    }
  },
  computed: {
    ...mapState({
      backgroundColors: state => state.background.colors // 背景颜色 数据
    })
  },
  methods: {
    /**
     * @description: 改变背景颜色
     * @param {string} color 要改变成的颜色，格式：#ffffff
     * @return {void}
     */
    changeBackgroundColor(color) {
      this.$store.commit(BACKGROUND_COLOR, color)
    },
    /**
     * @description: 添加背景颜色
     * @param {string} color 要添加成的颜色，格式：#ffffff
     * @return {void}
     */
    addBackgroundColor() {
      const color = this.$refs.input.value.trim()
      console.log(color)
      const reg = /^#[0-9a-fA-F]{6}$/
      if (reg.test(color)) {
        this.$store.commit(ADD_BACKGROUND_COLOR, color)
        this.isModalShow = false
      } else {
        window.alert('输入有误，请输入合法的6位RGB颜色，例如：#ffffff')
      }
    }
  }
}
</script>

<style lang="stylus">
#colors
  .add-color
    background-color #fff
    display flex
    justify-content center
    align-items center
    i.iconfont
      font-size 50px
      color #999
</style>